package org.wannatrak.android.service;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import org.wannatrak.android.ApplicationContext;
import org.wannatrak.android.executions.GPSBroadcastReceiver;
import org.wannatrak.android.helper.DateHelper;
import org.wannatrak.android.helper.WannatrakHelper;

import java.util.Date;

/**
 * @Author: Maksim Tulupov maxtulupov@gmail.com
 * @Date: $Date: 2011-11-29 05:19:42 +0000 (Tue, 29 Nov 2011) $ 5:28 PM
 * @version: $Revision: 32 $
 * @id: $Id: WannatrakGPSService.java 32 2011-11-29 05:19:42Z maxtulupov@gmail.com $
 */
public class WannatrakGPSService {

    private Context context;

    private PendingIntent pendingIntent;

    public WannatrakGPSService(Context context) {
        this.context = context;
    }

    public boolean startTracking() {
        String s = ApplicationContext.getSettingService().loadSetting("isTracking");
        boolean isTracking = Boolean.parseBoolean(s);
        if (isTracking) {
            Intent intent = new Intent(context, GPSBroadcastReceiver.class);
            AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            pendingIntent = PendingIntent.getBroadcast(
                    context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
            String interval = ApplicationContext.getSettingService().loadSetting("saveInterval");
            long intervalMillis = WannatrakHelper.convertStringIntervalInMillis(interval);
            Log.d(WannatrakGPSService.class.getSimpleName(), "save in db interval = " + intervalMillis);
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, DateHelper.getCurrentDateTime().getTime(),
                    intervalMillis, pendingIntent);
            return true;
        } else {
            Log.e(getClass().getSimpleName(), "tracking is disabled");
            return false;
        }
    }

    public void stopTracking() {
        if (pendingIntent != null) {
            AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            alarmManager.cancel(pendingIntent);
            pendingIntent = null;
            Intent intent = new Intent(context, GPSBroadcastReceiver.class).putExtra("stopTrack", true);
            PendingIntent pi = PendingIntent.getBroadcast(
                    context, 0, intent, PendingIntent.FLAG_ONE_SHOT);
            alarmManager.set(AlarmManager.RTC_WAKEUP, DateHelper.getCurrentDateTime().getTime() + 2, pi);
        }
    }
}
